<?php
class User extends AppModel {
	var $name = 'User';
	
	var $actsAs = array('Acl' => array('type' => 'requester'));
	
	function bindNode($user) {
    	return array('model' => 'Group', 'foreign_key' => $user['User']['group_id']);
  }
	
	function parentNode() {
		if (!$this->id && empty($this->data)) {
			return null;
		}
		if (isset($this->data['User']['group_id'])) {
			$groupId = $this->data['User']['group_id'];
		} else {
			$groupId = $this->field('group_id');
		}
		if (!$groupId) {
			return null;
		} else {
			return array('Group' => array('id' => $groupId));
		}
	}
	
	var $validate = array(
		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'A Username is required.'
			),
			'unique' => array(
				'rule' => array('isUnique'),
				'message' => 'Sorry that user name is in use.'
			)
		),
		'email' => array(
			'email1' => array(
				'rule' => array('email'),
				'message' => 'Please enter a valid email address.'
			)
		),
		'password' => array(
			'min6' => array(
				'rule' => array('minLength', 6),
				'message' => 'Please enter a password with at least 6 characters'
			)
		),
		'group_id' => array(
			'numeric' => array(
				'rule' => array('numeric')
			)
		)
	);

/**
* This model needs to create corresponding aco records as well.
*/

function afterSave($created) {
	//Need to create aco.
	if($created) {
		$this->Aco = ClassRegistry::init('Aco');
		$this->Aco->create(array('parent_id' => null, 
											 'model' => 'User', 
											 'foreign_key' => $this->id));
		$this->Aco->save();
	}
}

function afterDelete() {
	//need to delete aco.
	//Delete the aco node associated with the user.
	$this->Aco = ClassRegistry::init('Aco');
	$node = $this->Aco->node(array('model' => 'User', 'foreign_key' => $this->id));
	$nodeid = null;
	if($node)
		$nodeId = Set::extract($node, "0.Aco.id");
	if ($nodeId) {
		$this->Aco->delete($nodeId);
	}
	return true;
}

/**
* START ASSOCIATION INFORMATION
******************************************************************************
*/

	var $belongsTo = array(
		'Group' => array(
			'className' => 'Group',
			'foreignKey' => 'group_id'
		)
	);

	var $hasOne = array(
		'Application' => array(
			'className' => 'Application',
			'foreignKey' => 'user_id'
		)
	);

}
